#!/bin/python3

'''
mkfont_array.py
Convert a font file to a C array.

Install:
npm i lv_font_conv -g
pip install fontTools==4.56.0
'''

from fontTools import subset
from fontTools.ttLib import TTFont
import subprocess
import sys
import argparse
import os

def parse_args():
    parser = argparse.ArgumentParser(description="Font processing tool")
    parser.add_argument("--fontfile", 
                      type=str, 
                      default="SourceHanSerifSC-Regular.otf",
                      help="Input font file path (e.g. /fonts/SourceHanSerifSC-Regular.otf)")
    parser.add_argument("--charset",
                      type=str,
                      default="chars.txt",
                      help="Path to charset file (default: chars.txt)")
    parser.add_argument("--output_dir",
                      type=str,
                      default=os.path.dirname(os.path.abspath(__file__)),
                      help="Output directory path (default: current script directory)")
    parser.add_argument("--size",
                      type=int,
                      default=28,
                      help="Font size in pixels (default: 28)")
    parser.add_argument("--bpp",
                      type=int,
                      choices=[1, 2, 4, 8],
                      default=2,
                      help="Bits per pixel (default: 2)")
    parser.add_argument("--verbose",
                    action="store_true",
                    help="详细地列出处理的文件")
    return parser.parse_args()

def generate_filename(input_path, charset, size, bpp):
    base_name = os.path.basename(input_path)
    name_without_ext = os.path.splitext(base_name)[0]
    formatted = name_without_ext.replace("-", "_").lower()

    base_name = os.path.basename(charset)
    name_without_ext = os.path.splitext(base_name)[0]
    new_charset = name_without_ext.replace("-", "_").lower()

    return f"font_{formatted}_{new_charset}_{size}_{bpp}bpp.c"

def ensure_dir(path):
    if not os.path.exists(path):
        os.makedirs(path)
        print(f"Created directory: {path}")

def main():
    args = parse_args()
    
    # ================== 生成输出路径 ==================
    output_filename = generate_filename(args.fontfile, args.charset, args.size, args.bpp)
    output_path = os.path.join(args.output_dir, output_filename)
    ensure_dir(args.output_dir)
    
    # ================== 字体子集化 ==================
    try:
        font = TTFont(args.fontfile)
        
        options = subset.Options()
        options.flavor = "woff2"
        options.no_hinting = True
        
        # 修改点4：使用args.charset参数
        with open(args.charset, "r", encoding="utf-8") as f:
            text = f.read()
            glyphs = list({ord(c) for c in text})

        # 生成临时文件路径
        base_name = os.path.basename(args.fontfile)
        subset_name = os.path.splitext(base_name)[0] + "_subset.ttf"
        subset_path = os.path.join(args.output_dir, subset_name)

        if args.verbose:
            print(f"Subset start: ", os.path.basename(args.fontfile), "->", subset_name)
        subsetter = subset.Subsetter(options=options)
        subsetter.populate(unicodes=glyphs)
        subsetter.subset(font)
        font.save(subset_path)
        if args.verbose:
            print(f"Subset saved: {subset_path}")

    except Exception as e:
        print(f"Subset failed: {str(e)}")
        sys.exit(1)

    # ================== LVGL 转换 ==================
    try:
        cmd = [
            "npx", "lv_font_conv",
            "--font", subset_path,
            "--size", str(args.size),
            "--bpp", str(args.bpp),
            "--format", "lvgl",
            "--range", "0x20-0xFFFF",
            "--no-compress",
            "--output", output_path
        ]
        
        if args.verbose:
            print(f"Conversion start: {subset_name} -> {output_filename}")
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            check=True
        )

        if args.verbose:
            print(f"Conversion Output: {output_path}")
        # os.remove(subset_path)  #! 清理精简字体文件
        # print(f"removed file: {output_path}")
        
    except subprocess.CalledProcessError as e:
        print(f"Conversion error: {e.stderr}")
        sys.exit(1)
    except FileNotFoundError:
        print("Dependency required: npm install -g lv_font_conv")
        sys.exit(1)

if __name__ == "__main__":
    main()